package xin.nick.minicat;

import java.io.IOException;
import java.io.InputStream;
import java.lang.annotation.Retention;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author Nick
 * @date 2021/6/20
 * @description 把请求信息封装为 Request
 */
public class Request {

    private String method;
    private String url;
    private List<String> urls;
    private InputStream inputStream;
    private MiniCatContent miniCatContent;

    public MiniCatContent getMiniCatContent() {
        return miniCatContent;
    }

    public void setMiniCatContent(MiniCatContent miniCatContent) {
        this.miniCatContent = miniCatContent;
    }

    public String getMethod() {
        return method;
    }

    public void setMethod(String method) {
        this.method = method;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public List<String> getUrls() {
        return urls;
    }

    public void setUrls(List<String> urls) {
        this.urls = urls;
    }

    public InputStream getInputStream() {
        return inputStream;
    }

    public void setInputStream(InputStream inputStream) {
        this.inputStream = inputStream;
    }

    public Request() {

    }

    public Request(InputStream inputStream) throws IOException {

        this.inputStream = inputStream;

        int count = 0;
        // 网络请求的时候,可能数据还没有到达,所以在没有拿到之前先循环
        while (count == 0) {
            count = inputStream.available();
        }
        byte[] bytes = new byte[count];
        inputStream.read(bytes);
        String inputString = new String(bytes);

        // 拿到请求头
        String firstLineStr = inputString.split("\\n")[0];
        String[] httpFirstLineStringArray = firstLineStr.split(" ");

        this.method = httpFirstLineStringArray[0];
        this.url = httpFirstLineStringArray[1];
        if(Objects.nonNull(this.url)) {
            this.urls = Arrays.stream(this.url.split("/"))
                    .filter(s -> s.trim().length()>0)
                    .collect(Collectors.toList());

        }
    }
}
